package com.wl.boot.batch.service.impl;

import com.wl.boot.batch.bean.entity.CommonExcelConfig;
import com.wl.boot.batch.bean.entity.CommonExcelPageField;
import com.wl.boot.batch.mapper.excelMapper;
import com.wl.boot.batch.service.ExcelAsyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author wanglu
 * @date 2021-08-18 17:40
 */
@Service
public class ExcelAsyncServiceImpl implements ExcelAsyncService {
    private static Logger logger = LoggerFactory.getLogger(ExcelAsyncServiceImpl.class);

    @Autowired
    private excelMapper dao;

    @Override
    @Async("asyncServiceExecutor")
    public void Excel2DB(List<Object> list, CommonExcelConfig ec, List<CommonExcelPageField> epf, CountDownLatch countDownLatch) {
        logger.info(" 线程 -" + Thread.currentThread().getName() + " 正在执行插入");
        try {
            if (list.size() <= 3000) {
                dao.batchTargetTable(ec.getTargetTable(), list, epf);
            } else {
                int length = list.size();
                // 计算可以分成多少组
                int num = (length + 3000 - 1) / 3000;
                for (int i = 0; i < num; i++) {
                    // 开始位置
                    int fromIndex = i * 3000;
                    // 结束位置
                    int toIndex = (i + 1) * 3000 < length ? (i + 1) * 3000 : length;
                    dao.batchTargetTable(ec.getTargetTable(), list.subList(fromIndex, toIndex), epf);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            countDownLatch.countDown();
        }


    }
}
